import React from 'react';
import PropTypes from 'prop-types';
import {injectIntl} from './intl';
import {Tree, Spin, Modal, Row, Icon, Popover, Form, message} from 'antd';
const TreeNode = Tree.TreeNode;
import {union} from 'lodash';
import styles from './CategoryTree.css';
import {PERMISSION} from './constants';
import {
    FORM_BIG_OPTIONS
} from '../constants';
const FormItem = Form.Item;
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {getObjById, validateAddCategory} from './utils';
import TextInput from 'Shared/components/TextInput';
import {productCategoryType} from '../Enum';
import {conventEnumValueToString} from '../utils';
const dangerColor = '#ff4d4f';
const autosize = {minRows: 1};
const EMPTY_CATEGORY = {
    id: null,
    code: '',
    name: '',
    unitVolume: '',
    kdBomCode: '',
    isLeaf: false,
    remark: ''
};
const calcLink = (id, pages, paths) => {
    if(!id)
        return;
    for(let i = 0; i < pages.length; i++)
        /*eslint-disable  eqeqeq*/
        if(pages[i].id == id || (pages[i].items && calcLink(id, pages[i].items, paths))) {
            paths.push(`${pages[i].id}`);
            return true;
        }
};

export class CategoryTree extends React.PureComponent {
    static getDerivedStateFromProps(props, state) {
        if(props.locatedKey === state.locatedKey)
            return null;
        if(!props.locatedKey)
            return {locatedKey: null};
        const link = [];
        calcLink(props.locatedKey, props.pages, link);
        if(link.length === 0)
            return null;
        return {
            locatedKey: props.locatedKey,
            expandedKeys: union(state.expandedKeys, link.slice(1))
        };
    }
    constructor(props) {
        super(props);
        const link = [];
        this.state = {
            locatedKey: props.locatedKey ? props.locatedKey.toString() : '',
            expandedKeys: (props.locatedKey && calcLink(props.locatedKey, props.pages, link)) ? link.slice(1) : [],
            isReload: false,
            loading: false,
            showPanel: false,
            modal: {},
        };
        this.onExpand = this.onExpand.bind(this);
        this.onSelect = this.onSelect.bind(this);
        this.onLoadData = this.onLoadData.bind(this);
        this.renderTreeNodes = this.renderTreeNodes.bind(this);
    }

    componentDidMount() {
        this.props.init();
    }
    handleFilterChange = (value, name) => {
        const {category = {}} = this.state.modal;
        this.setState({
            modal: {
                ...this.state.modal,
                category: {
                    ...category,
                    [name]: value
                }
            }
        });
    }
    setQueryTop = () => {
        this.props.categoryProductSearch();
    }

    setAdding = id => {
        const category = getObjById(this.props.pages, id);
        this.setState({
            modal: {
                title: `${category.code}/${category.name} ${this.props.intl.formatMessage({
                    id: 'categoryTree.modle.setAdding',
                    defaultMessage: '新增子分类'
                })}`,
                category: {
                    ...EMPTY_CATEGORY,
                    parentId: category.id,
                    topType: category.type
                },
            },
            showPanel: true,
        });
    };

    setEditing = id => {
        this.setState({
            modal: {
                title: this.props.intl.formatMessage({
                    id: 'categoryTree.modle.setEditing',
                    defaultMessage: '编辑'
                }),
                category: getObjById(this.props.pages, id),
            },
            showPanel: true,
        });
    };

    renderTreeNodes(data = []) {
        const _ = this;
        return data.map(item => {
            const {items = [], options = []} = item;
            const str = `${item.code}/${item.name}`;
            const opts = [<span key="title" title={`${item.code}/${item.name}`}>
                {str}
            </span>];
            opts.push(
                <Popover trigger="click"
                    onClick={this.onClickPopover}
                    placement="rightTop"
                    overlayClassName={styles.categoryDetail}
                    key="info" title="详情"
                    content={<React.Fragment>
                        <Form className="form-standard">
                            <Row>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'categoryTree.modale.form.code',
                                        defaultMessage: '编号'
                                    })}
                                    {...FORM_BIG_OPTIONS.item}>
                                    {item.code}
                                </FormItem>
                            </Row>
                            <Row>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'categoryTree.modale.form.name',
                                        defaultMessage: '名称'
                                    })}
                                    {...FORM_BIG_OPTIONS.item}>
                                    {item.name}
                                </FormItem>
                            </Row>
                            <Row>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'categoryTree.modale.form.type',
                                        defaultMessage: '类型'
                                    })}
                                    {...FORM_BIG_OPTIONS.item}>
                                    {conventEnumValueToString(productCategoryType, item.type)}
                                </FormItem>
                            </Row>
                            {
                                item.type === productCategoryType.车型 &&
                                <Row>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'categoryTree.modale.unitVolume',
                                            defaultMessage: '单车体积(M3)'
                                        })}
                                        {...FORM_BIG_OPTIONS.item}>
                                        {item.unitVolume}
                                    </FormItem>
                                </Row>
                            }
                            {
                                item.type === productCategoryType.物料组 &&
                                <Row>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'categoryTree.modale.kdBomCode',
                                            defaultMessage: 'KDBOM号'
                                        })}
                                        {...FORM_BIG_OPTIONS.item}>
                                        {item.kdBomCode}
                                    </FormItem>
                                </Row>
                            }
                            <Row>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'categoryTree.modale.remark',
                                        defaultMessage: '备注'
                                    })}
                                    {...FORM_BIG_OPTIONS.item}>
                                    {item.remark}
                                </FormItem>
                            </Row>
                        </Form>
                    </React.Fragment>}>
                    {item.type !== productCategoryType.根 && <Icon key="info" data-id={item.id} data-mode="info" title="详情" type="info-circle" onClick={this.onOptClick} />}
                </Popover>
            );
            if(this.props.permissions.includes(PERMISSION.add) && (item.type !== productCategoryType.物料组))
                opts.push(<Icon key="add" data-id={item.id} data-mode="add" title={this.props.intl.formatMessage({
                    id: 'categoryTree.btn.add',
                    defaultMessage: '新增子分类'
                })} type="plus-circle" theme="twoTone" onClick={this.onOptClick} />);
         
            if(this.props.permissions.includes(PERMISSION.update) && options.includes(PERMISSION.update) && item.type !== productCategoryType.根)
                opts.push(<Icon key="edit" data-id={item.id} data-mode="edit" title={this.props.intl.formatMessage({
                    id: 'categoryTree.btn.edit',
                    defaultMessage: '编辑'
                })} type="edit" theme="twoTone" onClick={this.onOptClick} />);

            if(this.props.permissions.includes(PERMISSION.abandon) && options.includes(PERMISSION.abandon) && item.type !== productCategoryType.根)
                opts.push(
                    <span key="categoryAbandon" onClick={this.onClickPopover}>
                        <WrappedPopconfirm placement="rightTop" key="abandon" id={item.id} title={this.props.intl.formatMessage({
                            id: 'categoryTree.title.abandon',
                            defaultMessage: '确认作废产品分类？'
                        })} onConfirm={this.onClickAbandon}>
                            <Icon key="abandon" data-id={item.id} data-mode="abandon" title={this.props.intl.formatMessage({
                                id: 'categoryTree.btn.abandon',
                                defaultMessage: '作废'
                            })} type="stop" theme="twoTone" twoToneColor={dangerColor} onClick={this.onOptClick} />
                        </WrappedPopconfirm>
                    </span>
                );
            return (<TreeNode key={item.id}
                title={<span className={styles.span}>{opts}</span>}
                dataRef={item}
                isLeaf={item.isLeaf}
                selectable={_.props.selectable(item)}>
                {!item.isLeaf && this.renderTreeNodes(items)}
            </TreeNode>);
        });
    }

    onExpand(expandedKeys, {expanded, node}) {
        this.setState({expandedKeys});
        if(expanded)// && this.state.isReload
            this.onLoadData(node).then(() => {
                this.setState({isReload: false});
            });
    }

    onSelect(selectedKeys, e) {
        const id = e.selected ? selectedKeys[0] : this.props.locatedKey.toString();
        if(id !== this.props.locatedKey.toString())
            this.props.onSelect(id, e.node.props.dataRef);
    }

    onLoadData(node) {
        const data = node.props.dataRef;
        return data.items && data.items.length && data.items.every(item => !item.isNew)
            ? Promise.resolve()
            : this.props.onLoadData(data);
    }

    onReload = () => {
        this.props.onReload();
        this.setState({
            expandedKeys: [],
            isReload: true
        });
    }

    onOptClick = e => {
        const {id, mode} = e.currentTarget.dataset;
        switch(mode) {
            case 'add':
                this.setAdding(id);
                break;
            case 'edit':
                this.setEditing(id);
                break;
            case 'query':
                this.setQueryTop();
                break;
        }
        e.stopPropagation();
    }

    onClickAbandon = id => {
        this.setState({loading: true});
        return this.props.onClickAbandon(id).then(() => {
            this.setState({loading: false});
        });
    }
    
    onClickPopover = e => {
        e.stopPropagation();
    }

    onClose = () => {
        this.setState({
            modal: {},
            showPanel: false,
            isValidate: false,
        });
    }

    onSubmit = () => {
        const {category = {}} = this.state.modal;
        const {id, parentId, code, name, unitVolume, kdBomCode, remark, rowVersion, type = category.type ? category.type : category.topType + 1} = category;
        const result = validateAddCategory(category);
        if(result) {
            this.setState({isValidate: true});
            return message.warn(result);
        }
        this.setState({loading: true});
        return this.props.onSubmitCategory({
            parentId,
            code,
            name,
            remark,
            type,
            rowVersion,
            unitVolume,
            kdBomCode
        }, id).then(success => {
            this.setState({
                loading: false,
            });
            if(success)
                this.setState({
                    showPanel: false,
                    isValidate: false,
                });
        });
    }
    render() {
        const {category = {}} = this.state.modal;
        const treeNodes = this.renderTreeNodes(this.props.pages);
        if(this.props.permissions.includes(PERMISSION.update))
            treeNodes.push(<TreeNode key="query" selectable={false} title={<a data-mode="query" onClick={this.onOptClick}>
                {this.props.intl.formatMessage({
                    id: 'categoryTree.btn.query',
                    defaultMessage: '未设置分类产品'
                })}</a>} isLeaf={true} />);
        return (
            <React.Fragment>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <div className={styles.button}>
                        <a title={this.props.intl.formatMessage({
                            id: 'categoryTree.btn.reload',
                            defaultMessage: '刷新'
                        })}><Icon type="reload" onClick={this.onReload} /></a>
                    </div>
                    <Tree loadData={this.onLoadData} onExpand={this.onExpand} onSelect={this.onSelect}
                        expandedKeys={this.state.expandedKeys}
                        selectedKeys={this.props.locatedKey ? [this.props.locatedKey.toString()] : null}
                        autoExpandParent={false}>
                        {treeNodes}
                    </Tree>
                </Spin>
                <Modal key="modal"
                    title={this.state.modal.title}
                    visible={this.state.showPanel}
                    destroyOnClose={true}
                    maskClosable={false}
                    onOk={this.onSubmit}
                    confirmLoading={this.state.loading}
                    onCancel={this.onClose}>
                    <Form className="form-standard">
                        <Row>
                            <FormItem
                                validateStatus={this.state.isValidate && !category.code ? 'error' : null}
                                required
                                label={this.props.intl.formatMessage({
                                    id: 'categoryTree.modale.form.code',
                                    defaultMessage: '编号'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                <TextInput name="code"
                                    value={category.code} onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Row>
                        <Row>
                            <FormItem
                                validateStatus={this.state.isValidate && !category.name ? 'error' : null}
                                required
                                label={this.props.intl.formatMessage({
                                    id: 'categoryTree.modale.form.name',
                                    defaultMessage: '名称'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                <TextInput name="name"
                                    value={category.name} onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Row>
                        <Row>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'categoryTree.modale.form.type',
                                    defaultMessage: '类型'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                {conventEnumValueToString(productCategoryType, category.type ? category.type : category.topType + 1)}
                            </FormItem>
                        </Row>
                        {
                            (category.type ? category.type : category.topType + 1) === productCategoryType.车型 &&
                            <Row>
                                <FormItem
                                    validateStatus={this.state.isValidate && !category.unitVolume ? 'error' : null}
                                    required
                                    label={this.props.intl.formatMessage({
                                        id: 'categoryTree.modale.form.unitVolume',
                                        defaultMessage: '单车体积(M3)'
                                    })}
                                    {...FORM_BIG_OPTIONS.item}>
                                    <TextInput name="unitVolume"
                                        value={category.unitVolume} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Row>
                        }
                        {
                            (category.type ? category.type : category.topType + 1) === productCategoryType.物料组 &&
                            <Row>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'categoryTree.modale.form.kdBomCode',
                                        defaultMessage: 'KDBOM号'
                                    })}
                                    {...FORM_BIG_OPTIONS.item}>
                                    <TextInput name="kdBomCode"
                                        value={category.kdBomCode} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Row>
                        }
                        <Row>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'categoryTree.modale.form.remark',
                                    defaultMessage: '备注'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                <TextInput type="textarea" name="remark" autosize={autosize}
                                    value={category.remark} onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Row>
                    </Form>
                </Modal>
            </React.Fragment>
        );
    }
}

/**
 * 树形结构展示CategoryTree
 */
CategoryTree.propTypes = {
    categoryProductSearch: PropTypes.func,
    /**
     * 页面数据
     * pages: [{
     *      id: required,
     *      items: pages,    子节点
     *      name: required,     名称
     *      code: required,     编号
     *      isLeaf: required, 是否叶子节点
     * }]
     * }
     */
    init: PropTypes.func,
    /**
     * 展开节点需要异步获取数据时触发
     * @param node  节点数据
     */
    intl: PropTypes.object,
    /**
     * 选中节点时触发
     * @param id  当前选中节点的id
     */
    loading: PropTypes.bool,
    locatedKey: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.number
    ]),
    pages: PropTypes.array,
    /**
     * 设置节点是否可选择
     * @default true 默认可选中
     */
    permissions: PropTypes.array,
    selectable: PropTypes.func,
    onClickAbandon: PropTypes.func,
    onConditionsChange: PropTypes.func,
    onLoadData: PropTypes.func,
    onReload: PropTypes.func,
    onSelect: PropTypes.func,
    onSubmitCategory: PropTypes.func,
};

CategoryTree.defaultProps = {
    pages: [],
    locatedKey: '',
    onLoadData: () => Promise.resolve(),
    onSelect: () => Promise.resolve(),
    selectable: () => true
};


import {
    getCategoryChildren,
    categorySearch,
    getTopCategories,
    saveQueryCondition,
    onClickAbandonCategory,
    onSubmitCategory,
    categoryProductSearch
} from './actions';

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';

const dataSelector = selectorFactory(['page', 'domainData', 'categories', 'data']);

const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);

const locatedCategorySelector = createSelector(
    (state, ownProps) => dataSelector(state, ownProps),
    state => state.getIn(['page', 'appState', 'queryCondition', 'productCategoryId']),
    (categories, locatedKey) => {
        if(!locatedKey)
            return '';
        const category = getObjById(categories, locatedKey);
        return category.id;
    }
);

const mapStateToProps = (state, ownProps) => ({
    permissions: getPermissions(state),
    pages: dataSelector(state, ownProps),
    locatedKey: locatedCategorySelector(state, ownProps),
    loading: state.getIn(['page', 'domainData', 'categories', 'isFetching']),

});
const mapDispatchToProps = dispatch => ({
    init: () => dispatch(getTopCategories(false)),
    onSelect: id => {
        dispatch(categorySearch(id));
        dispatch(saveQueryCondition('isBound', true));
    },
    onLoadData: ({id}) => dispatch(getCategoryChildren(id)),
    onConditionsChange: (value, name) => dispatch(saveQueryCondition(name, value)),
    onReload: () => {
        dispatch(getTopCategories(true));
        dispatch(saveQueryCondition('productCategoryId', ''));
    },
    onClickAbandon: id => dispatch(onClickAbandonCategory(id)),
    onSubmitCategory: (data, id) => dispatch(onSubmitCategory(data, id)),
    categoryProductSearch: () => {
        dispatch(categoryProductSearch());
        dispatch(saveQueryCondition('isBound', false));
    }
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(CategoryTree));
